package com.wHitE.servlet;

import com.google.gson.Gson;
import com.wHitE.utils.Result;
import com.wHitE.service.LoginService;

import com.wHitE.service.impl.LoginServiceImpl;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private LoginService loginService = new LoginServiceImpl();

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("登录接口初始化...");
        super.init(config);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("登录接口调用...");
        super.service(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取out对象
        PrintWriter out = resp.getWriter();

        //获取全部参数map
        //        Map<String, String[]> parameterMap = req.getParameterMap();
        //        Set<String> keySet = parameterMap.keySet();
        //        for (String key : keySet) {
        //            String[] values = parameterMap.get(key);
        //            System.out.println(key + ":");
        //            for (String value : values) {
        //                System.out.println(value + " ");
        //            }
        //        }

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 创建session对象
        HttpSession session = req.getSession();

        //创建cookie对象
        Cookie cookie = new Cookie("isLogin", "true");
        cookie.setMaxAge(900);

        // 创建application对象
        ServletContext application = this.getServletContext();
        application.setAttribute("msg", "application");

        // 初始化 object=>json 对象
        Gson gson = new Gson();

        // 判断是否登录成功...并响应给前端
        String msg = loginService.userLogin(username, password);
        if (msg.equals("success")) {
            out.print(gson.toJson(Result.success()));
            session.setAttribute("username", username);
            resp.addCookie(cookie);
        } else {
            out.print(gson.toJson(Result.error(msg)));
        }
    }

    @Override
    public void destroy() {
        System.out.println("登录接口关闭...");
    }
}
